package com.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.entity.College;
import com.entity.CollegeSort;
import com.excel.StudentExcel;
import com.excel.StudentListener;
import com.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    /**
     * 通过excel表插入数据
     */
    @RequestMapping(path = "/test",
            method = RequestMethod.POST)
    public synchronized void insert(MultipartFile multipartFile, HttpServletResponse response) throws IOException {
        InputStream inputStream = multipartFile.getInputStream();
        // 查询CollegeSort对象，用于判断excel中的数据是否正确
        Map<String, CollegeSort> map = studentService.queryCollegeSort();
        // 查询学号
        List<String> list = studentService.queryStudentNumberAll();
        // 查询身份证
        List<String> identityAll = studentService.queryStudentIdentityAll();
        // 通过EasyExcel工具读取excel表中内容
        EasyExcel
                .read(
                        inputStream,
                        StudentExcel.class,
                        // 监听器
                        new StudentListener(
                                map,
                                list,
                                identityAll,
                                response,
                                studentService)
                ).sheet().doRead();
        System.out.println("执行完毕");
    }

    /**
     * 下载目录下的test.xlsx文件
     */
    @RequestMapping(path = "/download")
    public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取upload下的test.xlsx文件
        ClassPathResource resource = new ClassPathResource("/upload/test.xlsx");
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        File file = resource.getFile();
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + URLEncoder.encode(file.getName(), "UTF-8"));
        BufferedInputStream bis = new BufferedInputStream(resource.getInputStream());
        byte[] buff = new byte[1024];
        OutputStream os = response.getOutputStream();
        int i = 0;
        while ((i = bis.read(buff)) != -1) {
            os.write(buff, 0, i);
            os.flush();
        }
        bis.close();
        os.close();
    }

    /**
     * 下载模板
     */
    @RequestMapping("/downloadModel")
    public void downloadModel(HttpServletResponse response) throws IOException {
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + URLEncoder.encode("模板.xlsx", "UTF-8"));
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet sheet = EasyExcel.writerSheet(0).head(StudentExcel.class).build();
        excelWriter.write(Collections.emptyList(), sheet);
        excelWriter.finish();
    }

    /**
     * 导出数据
     */
    @RequestMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        long l = studentService.countStudent();
        long n = l / 50000;
        n += (l % 50000 == 0 ? 0 : 1);
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + URLEncoder.encode("学生信息.xlsx", "UTF-8"));
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet sheet = EasyExcel.writerSheet(0).head(StudentExcel.class).build();
        for (int i = 1; i <= n; i++) {
            List<StudentExcel> list = studentService.queryStudentLimit(i, 500000);
            excelWriter.write(list, sheet);
        }
        excelWriter.finish();
    }
}
